package at.austria.leecher.pages;

import at.austria.leecher.model.SingleRank;
import org.apache.log4j.Logger;
import org.openqa.selenium.By;
import org.openqa.selenium.WebElement;

import java.util.ArrayList;
import java.util.List;

public class SingleChartsPage extends LeecherPage {

    private static final Logger LOG = Logger.getLogger( SingleChartsPage.class );

    private static final String URL_OE3_AUSTRIA_SINGLE_CHARTS = "http://oe3.orf.at/charts/stories/single";

    private List<SingleRank> singles = new ArrayList<SingleRank>();

    @Override
    public void start() throws Exception {
        LOG.debug( String.format( "%s started ...", getClass().getSimpleName() ) );
        try {
            driver.get( URL_OE3_AUSTRIA_SINGLE_CHARTS );

            final WebElement tableCharts = driver.findElement( By.xpath( "//table[@class='charts']" ) );
            final WebElement body = tableCharts.findElement( By.tagName( "tbody" ) );
            final List<WebElement> entries = body.findElements( By.tagName( "tr" ) );

            for ( final WebElement entry : entries ) {
                final List<WebElement> columns = entry.findElements( By.tagName( "td" ) );

                final int rank = Integer.valueOf( columns.get( 1 ).getText() );
                final String interpret = columns.get( 4 ).getText();
                final String title = columns.get( 5 ).getText();

                singles.add( new SingleRank( interpret, title, rank ) );
                LOG.info( String.format( "%2d: %s - %s", rank, interpret, title ) );
            }
        } catch ( final Exception e ) {
            e.printStackTrace();
            throw e;
        } finally {
            // should be called in every run method
            LOG.debug( String.format( "%s finished ...", getClass().getSimpleName() ) );
            this.finish();
        }
    }

    @Override
    public String toString() {
        final StringBuilder sb = new StringBuilder();
        sb.append( String.format( "Duration: %d msec", this.getDuration() ) );
        if ( !this.completedSuccessfully() ) {
            sb.append( String.format( "\nError occured: %s", this.occuredException ) );
        }
        return sb.toString();
    }
}
